package com.ykh.config;

import com.alibaba.fastjson.JSON;
import com.ykh.pojo.po.User;
import com.ykh.pojo.vo.ErrorCode;
import com.ykh.pojo.vo.Result;
import com.ykh.service.UserService;
import com.ykh.util.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
@Component
@Slf4j //日志的注释
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //在执行controller方法(Handler)之前执行
        /**
         * 1. 需要判断 ,请求的接口路径 是否为 HandlerMethod (controller 方法)
         * 2. 判断 token 是否为空, 如果为空 未登录
         * 3. 如果token 不为空, 登录验证 loginService checkToken
         * 4. 如果认证成功 ,放行即可
         */
        //1.判断 ,请求的接口路径 是否为 HandlerMethod (controller 方法)
        if (!(handler instanceof HandlerMethod)){
            //hander 可能是 RequestResourceHandler springboot 程序,访问静态资源 默认去classpath 下的static 目录去查询
            return true;
        }
        //拿到token
        String token = request.getHeader("Authorization");
        //日志
        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");

        //2. 判断 token 是否为空, 如果为空 未登录
        if (token == null){
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        //3. token不为空, 进行登录验证 loginService checkToken
        User user = userService.checkToken(token);
        if (user == null){
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        //是登录状态，放行
        //希望在controller中直接获取用户信息, 如何获取?
        UserThreadLocal.put(user);
        return true;
    }

    //执行结束后要关闭本地线程, 防止内存泄漏
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}